package com.jic.market.controller.manage;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.market.api.manage.LotteryActivityApi;
import com.jic.market.common.exception.MarketException;
import com.jic.market.common.util.BeanUtil;
import com.jic.market.entity.LotteryTheme;
import com.jic.market.enums.LotteryDrawResultCode;
import com.jic.market.exception.LotteryDrawException;
import com.jic.market.request.manager.lottery.*;
import com.jic.market.request.rest.lottery.LotteryActivityInfoRestRequest;
import com.jic.market.request.rest.lottery.LotteryReceiverRequest;
import com.jic.market.response.manager.lottery.LotteryActivityResponse;
import com.jic.market.response.manager.lottery.LotteryDrawRecordResponse;
import com.jic.market.response.manager.lottery.LotteryThemeResponse;
import com.jic.market.response.rest.lottery.LotteryActivityInfoRestResponse;
import com.jic.market.response.rest.lottery.LotteryDrawRestResponse;
import com.jic.market.service.LotteryActivityService;
import com.jic.market.service.LotteryDrawRecordService;
import com.jic.market.service.LotteryThemeService;
import com.jic.market.service.rest.lottery.LotteryActivityInfoRestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: MJ
 * @date: 2020-03-02
 * @remark: 抽奖活动创建、编辑、复制功能等后台服务
 */
@RestController
@RequestMapping("/lotteryActivity")
@Api(tags = {"抽奖活动创建、编辑、复制功能等后台服务"})
@Slf4j
public class LotteryActivityController implements LotteryActivityApi {

    private final static Logger logger = LoggerFactory.getLogger(LotteryActivityController.class);

    @Resource
    private LotteryActivityService lotteryActivityService;

    @Resource
    private LotteryThemeService lotteryThemeService;

    @Resource
    private LotteryDrawRecordService lotteryDrawRecordService;

    @Resource
    private LotteryActivityInfoRestService lotteryActivityInfoRestService;

    //是否返回模板信息配置
    public static final int PAGE_TEMP_1 = 1;

    public static final int PAGE_TEMP_2 = 2;

    /**
     * 查询抽奖活动列表
     * @param form
     * @return
     */
    @PostMapping("/queryLotteryThemeList")
    @ResponseBody
    @ApiOperation(value = "查询抽奖活动列表")
    @Override
    public RestResult<PageResult<LotteryThemeResponse>> queryList(@RequestBody LotteryThemeInquireRequest form) {
        try {
            log.info("分页查询抽奖活动，入参{}", JSON.toJSONString(form));
            Page page = new Page();
            page.setLimit(form.getLimit());
            page.setStart(form.getStart());
            LotteryThemeInquireRequest lotteryThemeInquireRequest = BeanUtil.copy(form, LotteryThemeInquireRequest.class);
            PageResult<LotteryTheme> result = lotteryThemeService.queryPage(lotteryThemeInquireRequest, page);

            List<LotteryThemeResponse> lotteryThemeResponseList = result.getRows().stream().map(temp -> {
                LotteryThemeResponse lotteryThemeResponse = BeanUtil.copy(temp, LotteryThemeResponse.class);
//                lotteryThemeResponse.setEditFlag(lotteryThemeResponse.getDeptId().equals(form.getAdminOperate().getDeptId()) ? true : false);
                return lotteryThemeResponse;
            }).filter(item -> item != null).collect(Collectors.toList());
            PageResult<LotteryThemeResponse> pageResult = new PageResult<>();
            pageResult.setRows(lotteryThemeResponseList);
            pageResult.setTotal(result.getTotal());
            log.info("分页查询抽奖活动，入参{}", JSON.toJSONString(pageResult));
            return RestResult.success(pageResult);
        }catch (Exception e){
            log.error("Market queryLotteryThemeList error：",e);
            return RestResult.error("9999","系统异常，列表查询失败");
        }
    }


    /**
     * 抽奖活动详情页查询
     * @param request
     * @return
     */
    @PostMapping("/getLotteryThemeInfo")
    @ResponseBody
    @ApiOperation(value = "抽奖活动详情页查询")
    @Override
    public RestResult<LotteryActivityResponse> getLotteryThemeInfo(@RequestBody LotteryThemeRequest request) {
        try {
            log.debug("getLotteryThemeInfo " + request);
            LotteryActivityResponse lotteryActivityResponse = lotteryActivityService.getLotteryActivityInfo(request);
            return RestResult.success(lotteryActivityResponse);
        }catch (Exception e){
            log.error("Market getLotteryThemeInfo error：",e);
            return RestResult.error("9999","系统异常，抽奖活动详情查询失败");
        }
    }

    /**
     * 查询抽奖活动统计数据
     * @param form
     * @return
     */
    @PostMapping("/getLotteryDrawRecordList")
    @ResponseBody
    @ApiOperation(value = "查询抽奖活动统计数据")
    @Override
    public RestResult<PageResult<LotteryDrawRecordResponse>> getLotteryDrawRecordList(@RequestBody LotteryDrawRecordRequest form) {
        try {
            log.debug("getLotteryDrawRecordList " + form);
            Page page = new Page();
            page.setLimit(form.getLimit());
            page.setStart(form.getStart());
            LotteryDrawRecordRequest lotteryDrawRecordRequest = BeanUtil.copy(form, LotteryDrawRecordRequest.class);
            PageResult<LotteryDrawRecordResponse> result = lotteryDrawRecordService.queryPage(lotteryDrawRecordRequest, page);
            return RestResult.success(result);
        }catch (Exception e){
            log.error("Market getLotteryDrawRecordList error：",e);
            return RestResult.error("9999","系统异常，抽奖活动记录查询失败");
        }
    }


    /**
     * 创建抽奖活动-设置抽奖规则
     * @param form
     * @return
     */
    @PostMapping("/saveLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "创建抽奖活动-设置抽奖规则")
    @Override
    public RestResult<Long> saveLotteryActivity(@RequestBody LotteryActivityRequest form) {
        try {
            log.debug("saveLotteryActivity " + form);
            long id = lotteryActivityService.saveLotteryActivity(form);
            return RestResult.success(id);
        }catch (Exception e){
            log.error("Market saveLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }

    /**
     * 创建抽奖活动-奖品设置
     * @param form
     * @return
     */
    @PostMapping("/saveLotteryAwards")
    @ResponseBody
    @ApiOperation(value = "创建抽奖活动-奖品设置")
    @Override
    public RestResult<Integer> saveLotteryAwards(@RequestBody LotteryAwardsListRequest form) {
        try {
            log.debug("saveLotteryAwards " + form);
            Integer status = lotteryActivityService.saveLotteryAwards(form);
            return RestResult.success(status);
        }catch (Exception e){
            log.error("Market saveLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }

    /**
     * 编辑抽奖活动
     * @param request
     * @return
     */
    @PostMapping("/updateLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "编辑抽奖活动")
    @Override
    public RestResult<LotteryActivityResponse> updateLotteryActivity(@RequestBody LotteryActivityRequest request) {
        try {
            log.debug("updateLotteryActivity " + request);
            long id = lotteryActivityService.updateLotteryActivity(request);
            return RestResult.success(new LotteryActivityResponse());
        }catch (Exception e){
            log.error("Market saveLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }

    /**
     * 编辑抽奖活动-抽奖奖项设置
     * @param form
     * @return
     */
    @PostMapping("/updateLotteryAwards")
    @ResponseBody
    @ApiOperation(value = "编辑抽奖活动-抽奖奖项设置")
    @Override
    public RestResult<Integer> updateLotteryAwards(@RequestBody LotteryAwardsListRequest form) {
        try {
            log.debug("updateLotteryActivity " + form);
            Integer status = lotteryActivityService.updateLotteryAwards(form);
            return RestResult.success(status);
        }catch (Exception e){
            log.error("Market updateLotteryAwards error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }

    /**
     * 复制抽奖活动
     * @param request
     * @return
     */
    @PostMapping("/copyLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "复制抽奖活动")
    @Override
    public RestResult<Long> copyLotteryActivity(@RequestBody LotteryActivityRequest request) {
        try {
            long id = lotteryActivityService.copyLotteryActivity(request);
            return RestResult.success(id);
        }catch (Exception e){
            log.error("Market copyLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }

    /**
     * 保存为模板
     * @param request
     * @return
     */
    @ApiOperation(value = "保存为模板")
    @PostMapping("saveTemplate")
    @ResponseBody
    @Override
    public RestResult<Long> saveTemplate(@RequestBody LotteryTemplateRequest request) {
        try {

            Long id = lotteryActivityService.saveTemplate(request);
            return RestResult.success(id);
        }catch (MarketException me){
            return RestResult.error("9999",me.getMessage());
        }catch (Exception e){
            log.error("Market saveTemplate error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
     }

    /**
     * 删除抽奖活动
     * @param request
     * @return
     */
    @PostMapping("/deleteLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "删除抽奖活动")
    @Override
    public RestResult<String> deleteLotteryActivity(@RequestBody LotteryActivityRequest request) {
        lotteryActivityService.deleteLotteryActivity(request);
        return RestResult.success("成功");
    }

    /**
     * 关闭抽奖活动
     * 暂未有特殊逻辑 关闭活动 提交审核公用
     * 只做状态更改
     * @param request
     * @return
     */
    @PostMapping("/closeLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "关闭抽奖活动")
    @Override
    public RestResult<String> closeLotteryActivity(@RequestBody LotteryThemeRequest request) {
        try {
            LotteryThemeRequest param = new LotteryThemeRequest();
            param.setId(request.getId());
            param.setStatus(request.getStatus());
            param.setUpdater(request.getUpdater());
            param.setUpdaterName(request.getUpdaterName());
            lotteryThemeService.update(param);
            return RestResult.success("成功");
        }catch (Exception e){
            log.error("Market closeLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }



    /**
     * 审核
     * @param request
     * @return
     */
    @PostMapping("/verifyLotteryActivity")
    @ResponseBody
    @ApiOperation(value = "审核")
    @Override
    public RestResult<String> verifyLotteryActivity(@RequestBody LotteryThemeRequest request) {
        try {
            lotteryActivityService.verifyLotteryActivity(request);
            return RestResult.success("成功");
        }catch (Exception e){
            log.error("Market closeLotteryActivity error：",e);
            return RestResult.error("9999","系统异常，操作失败");
        }
    }



    @PostMapping("/lotteryInfoByTemp")
    @ApiOperation(value = "抽奖活动信息")
    public RestResult<LotteryActivityInfoRestResponse> getLotteryAwardsListByTemp(@RequestBody LotteryActivityInfoRestRequest request) {
        try {
            LotteryActivityInfoRestResponse restResponse = lotteryActivityInfoRestService.lotteryInfoByTemp(request);
            return RestResult.success(restResponse);
        }catch (LotteryDrawException e){
            log.info(e.getMessage());
            return RestResult.error(e.getRespCode(),e.getLocalizedMessage());
        }
    }



    /**
     * 大转盘模板渲染页面
     * @param request
     * @return
     */
    @PostMapping("/drawLotteryByTemp")
    @ApiOperation(value = "点击抽奖-转盘模版对接")
    public RestResult<LotteryDrawRestResponse> drawLotteryByTemp(@RequestBody LotteryActivityInfoRestRequest request) {
        LotteryDrawRestResponse lotteryDrawRestResponse = new LotteryDrawRestResponse();
        try {
            lotteryDrawRestResponse = lotteryActivityInfoRestService.drawLotteryByTemp(request);
            return RestResult.success(lotteryDrawRestResponse);
        }catch (LotteryDrawException e){
            log.info(e.getMessage());
            lotteryDrawRestResponse.setDrawResultCode(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getCode());
            lotteryDrawRestResponse.setDrawResultDesc(LotteryDrawResultCode.LOTTERY_DRAW_RESULT_NOT_WINNING.getMsg());
            return RestResult.success(lotteryDrawRestResponse);
        }
    }



    @PostMapping("/saveReceiverAddressByTemp")
    @ApiOperation(value = "保存中奖收货地址")
    public RestResult<String> saveReceiverAddress(@RequestBody LotteryReceiverRequest request) {
        try {
            log.debug("queryLotteryThemeList " + request);
            RestResult restResult = lotteryActivityInfoRestService.saveReceiverAddress(request);
            return restResult;
        }catch (LotteryDrawException e){
            log.info(e.getMessage());
            return RestResult.error(e.getRespCode(),e.getLocalizedMessage());
        }
    }



}
